package br.com.covosys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import br.com.covosys.exception.ApplicationException;
import br.com.covosys.model.MenuModel;
import br.com.covosys.model.ModelException;
import br.com.covosys.model.bean.Link;
import br.com.covosys.model.bean.Menu;
import br.com.covosys.util.SpringFactory;

@Scope("session")
@Controller
@SuppressWarnings("serial")
public class MenuController extends GenericController<Menu, MenuModel> {
	
	@Autowired
	public MenuController(MenuModel menuModel) {
		super(menuModel);
		setBean(new Menu());
		setList(new ArrayList<Menu>());
		setFilter(new HashMap<String, Object>());
	}
	
	@Override
	public void clean() throws ModelException, ApplicationException {
		super.clean();
		getBean().setLinks(new TreeSet<Link>());
	}
	
	public List<Menu> getListForShow() throws ModelException {
		return getModel().list();
	}
	
	public String add() throws ModelException, ApplicationException {
		
		String add = super.add();
		
		LinkController linkController = (LinkController) SpringFactory.getController(Link.class);
		linkController.clean();
		linkController.setList(new LinkedList<Link>());
		
		return add;
	}
	
	@Override
	public String edit() throws ModelException, ApplicationException {

		String edit = super.edit();
		
		LinkController linkController = (LinkController) SpringFactory.getController(Link.class);
		linkController.clean();
		linkController.setList(new LinkedList<Link>(bean.getLinks()));
		
		return edit;
	}
	
	@SuppressWarnings({"unchecked", "rawtypes"})
	public String save() throws ModelException, ApplicationException {
		
		LinkController linkController = (LinkController) SpringFactory.getController(Link.class);
		Set<Link> links = new TreeSet(linkController.getList());
		getBean().setLinks(links);
		
		String save = super.save();
		
		return save;
	}
}
